// page/component/new-pages/cart/cart.js
const app = getApp();
var url = app.globalData.url;
Page({
  data: {
    listcart: [],               // 购物车列表
    hasList: false,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    selectAllStatus: true,    // 全选状态，默认全选
    obj: {
      name: "hello"
    },
    item: [],
    goodsList:''
  },
  onShow: function () {
    //购物车列表
    this.show();
  },
  /* 清空购物车*/
  empty: function () {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定清空？',
      showCancel: true,
      success: function(res) {
        if(res.confirm){
          wx.request({
            url: url + 'clearGoodsInCartDing',
            data: {
            },
            header: {
              "Content-Type": "application/json"
            },
            success: function (res) {              
              if (res.data.object == true) {
                wx.showToast({
                  title: '删除成功！',
                  icon: '',
                  image: '',
                  duration: 2000,
                  mask: true,
                  success: function (res) {
                    that.show();
                    that.getTotalPrice();
                    that.setData({
                      listcart:''
                    })
                  },
                  fail: function (res) { },
                  complete: function (res) { },
                });
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: '',
                  image: '',
                  duration: 2000,
                  mask: true,
                  success: function (res) { },
                  fail: function (res) { },
                  complete: function (res) { },
                });
              }
            }
          });
        }else{
          console.log("取消清空")
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
    
  },
  /* 批量删除购物车*/
  Batchdelete: function () {
    var that = this;
    let listcart = this.data.listcart;
    let arr = [];
    console.log(listcart);
    for (let i = 0; i < listcart.length; i++) {
      if (listcart[i].checked) {
        arr.push(listcart[i].recId);
      }
    }
    that.setData({
      item: arr,
    });
    var list = this.data.item;
    console.log(list);
    wx.request({
      url: url + 'deleteGoodsInCartDingByRecId',
      data: {
        list: list
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        that.setData({
          selectAllStatus: true,    // 全选状态，默认全选
        });
        that.show();
        that.getTotalPrice();
        if (res.data.object == true) {
          wx.showToast({
            title: '删除成功！',
            icon: '',
            image: '',
            duration: 2000,
            mask: true,
            success: function (res) { 
              that.setData({
                listcart: ''
              })
            },
            fail: function (res) { },
            complete: function (res) { },
          });
        } else {
          wx.showToast({
            title: '删除失败',
            icon: '',
            image: '',
            duration: 2000,
            mask: true,
            success: function (res) { },
            fail: function (res) { },
            complete: function (res) { },
          })
        }
    } 
    });
},
  //结算
  pay:function () {
    var that = this;
    let listcart = this.data.listcart;
    let arr = [];
    console.log(listcart);
    for (let i = 0; i < listcart.length; i++) {
      if (listcart[i].checked) {
        arr.push(listcart[i]);
      }
    }
    that.setData({
      item: arr,
    });
    var list = JSON.stringify(this.data.item);
    console.log(list);
    wx.navigateTo({
      url: '../makeorder/makeorder?list='+list,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  show:function () {
    //购物车列表
    var that = this;
    const userid = app.globalData.userid;
    wx.request({
      url: url + 'getShopCart',
      data: {
        userId: userid,
        cartType: 1,
        pageIndex:1 ,
        pageSize:100
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        console.log(res.data.object.cartList);
        that.setData({
           hasList: true,
           listcart: res.data.object.cartList,
        });
        that.getTotalPrice();
      }
    });
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let listcart = this.data.listcart;
    const checked = listcart[index].checked;
    listcart[index].checked = !checked;
    this.setData({
      listcart: listcart
    });
    this.getTotalPrice();
  },
  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let listcart = this.data.listcart;
    for(let i = 0; i <listcart.length; i++) {
  listcart[i].checked = selectAllStatus;
}
this.setData({
  selectAllStatus: selectAllStatus,
  listcart: listcart
});
this.getTotalPrice();
  },

/**
 * 绑定加数量事件
 */
addCount(e) {
  const id = e.currentTarget.dataset.id;
  const index = e.currentTarget.dataset.index;
  let listcart = this.data.listcart;
  let goodsNumber = listcart[index].goodsNumber;
  goodsNumber = goodsNumber + 1;
  listcart[index].goodsNumber = goodsNumber;
  var that = this;
  wx.request({
    url: url + 'updateGoodsNumberInCartDing',
    data: {
      recId: id,
      goodsNumber: goodsNumber
    },
    header: {
      "Content-Type": "application/json"
    },
    success: function (res) {
      that.show();
      that.getTotalPrice();
    }
  });
},

/**
 * 绑定减数量事件
 */
minusCount(e) {
  var that = this;
  const recId = e.currentTarget.dataset.recid;
  const index = e.currentTarget.dataset.index;
  const obj = e.currentTarget.dataset.obj;
  let listcart = this.data.listcart;
  let goodsNumber = listcart[index].goodsNumber;
  if (goodsNumber <= 1) {
    return false;
  }
  goodsNumber = goodsNumber - 1;
  listcart[index].goodsNumber = goodsNumber;
  var that = this;
  wx.request({
    url: url + 'updateGoodsNumberInCartDing',
    data: {
      recId: recId,
      goodsNumber: goodsNumber
    },
    header: {
      "Content-Type": "application/json"
    },
    success: function (res) {
      console.log(res.data.object)
      that.show();
      that.getTotalPrice();
    }
  });
},

/**
 * 计算总价
 */
getTotalPrice() {
  var that = this;
  var listcart = this.data.listcart; // 获取购物车列表
  var total = 0;
  if(listcart != undefined){
    for (var i = 0; i < listcart.length; i++) {       
       // 循环列表得到每个数据
      if (listcart[i].checked) {                    
       // 判断选中才会计算价格
        total += listcart[i].goodsNumber * listcart[i].goodsPrice;
        // 所有价格加起来
      }
    }
  }else{
    console.log("undefind")
  }
  that.setData({                               
    // 最后赋值到data中渲染到页面
    listcart: listcart,
    totalPrice: total.toFixed(2)
  });
}
})